package com.kun.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kun.domain.${Domain};
import com.kun.domain.${Domain}Example;
import com.kun.mapper.${Domain}Mapper;
import com.kun.req.${Domain}QueryReq;
import com.kun.req.${Domain}SaveReq;
import com.kun.resp.PageResp;
import com.kun.resp.${Domain}QueryResp;
import com.kun.util.SnowUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @className: ${Domain}Service
 * @Description: ...
 * @author: kunkun
 * @date: 2025/7/9 13:08
 */
@Service
public class ${Domain}Service {
    @Autowired
    private ${Domain}Mapper ${domain}Mapper;

    private Logger LOG = LoggerFactory.getLogger(${Domain}Service.class);


    public void save(${Domain}SaveReq saveReq){
        DateTime date = DateUtil.date();
        ${Domain} ${domain} = BeanUtil.copyProperties(saveReq, ${Domain}.class);
        if(ObjectUtil.isNotNull(saveReq.getId())){  //编辑
            ${domain}.setUpdateTime(date);
            ${domain}Mapper.updateByPrimaryKeySelective(${domain});
        }  else {       //新增
            ${domain}.setId(SnowUtil.getSnowflakeNextId());
            ${domain}.setCreateTime(date);
            ${domain}.setUpdateTime(date);
            ${domain}Mapper.insert(${domain});
        }
    }

    public PageResp<${Domain}QueryResp> queryList(${Domain}QueryReq ${domain}QueryReq){

        ${Domain}Example ${domain}Example = new ${Domain}Example();
        ${Domain}Example.Criteria criteria = ${domain}Example.createCriteria();
        if (ObjectUtil.isNotNull(${domain}QueryReq.getMemberId())){
            criteria.andMemberIdEqualTo(${domain}QueryReq.getMemberId());
        }
        ${domain}Example.setOrderByClause("id desc");
        PageHelper.startPage(${domain}QueryReq.getPage(),${domain}QueryReq.getSize());
        List<${Domain}> ${domain}s = ${domain}Mapper.selectByExample(${domain}Example);
        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}s);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());

        List<${Domain}QueryResp> list = BeanUtil.copyToList(${domain}s, ${Domain}QueryResp.class);

        PageResp<${Domain}QueryResp> resp = new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setList(list);

        return resp;
    }


    public void delete(Long id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}